<template>
	<div id="index">
		<a-layout>
			<a-config-provider :locale="language">
				<a-layout-header>
					<a-steps changeable :current="currentStep" style="margin-bottom: 2%;">
						<a-step description="确保收货人信息无误">填写并选择收货人</a-step>
						<a-step description="确保商品清单信息无误">确认你的商品清单</a-step>
						<a-step description="你应该在信息正确后提交">提交你的订单</a-step>
					</a-steps>
					<a-list style="margin-bottom: 2%;">
						<a-list-item style="height:auto;" v-if="currentStep == 1">
							<a-row style="height: 24px;">
								<a-col :span="12" style="text-align: left;">
									<a-typography-title :heading="7" style="font-weight: bold;margin-top: 0%;">
										收货人信息
									</a-typography-title>
								</a-col>
								<a-col :span="12" style="text-align: right;">
									<a-typography-text type="primary" style="margin-top: 0%;cursor: pointer;"
										@click="insertAddress">
										新增收货地址
									</a-typography-text>
								</a-col>
							</a-row>
							<!--收货地址表单,1为新增,0为修改-->
							<userAddressForm :formVisible="addressformVisible" :addressForm="addressForm"
								@getaddressFormVisible="addressVisible" @refurshAddressList="refurshAddressList" :uId="uId" 
								:status="status" :currentAddress="currentAddress">
							</userAddressForm>

							<div style="overflow: auto;min-height: 60px;max-height: 90px;"
								v-show="addressList.data.length > 0" v-if="addressList.data">
								<a-row style="margin-top: 0.5%;margin-bottom:1%;cursor: pointer;"
									v-for="(item,index) in addressList.data" @mouseover="hoverReceiver(item)"
									@mouseleave="leaveReceiver(item)">
									<a-col :span="4" style="text-align: left;white-space: nowrap;text-indent: 1em;">
										<a-typography-title class="address-info" :heading="7"
											@click="chooseReceiver(item)">
											<div
												style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;width: 165px;">
												{{item.name}} {{item.telePhone}}
											</div>
											<span v-if="currentcheckedId == item.addressId">
												<div id="triangle"></div>
												<div class="check">
													<icon-check />
												</div>
											</span>
										</a-typography-title>
									</a-col>
									<a-col :span="20" style="text-align: left;text-indent: 1em;">
										<a-typography-title class="address-detail" :heading="7" ellipsis>
											{{item.address}}
											<a-tag style="text-indent: 0em;" v-if="item.isDefault == 1">
												<template #icon>
													<icon-check-circle-fill />
												</template>
												默认地址
											</a-tag>
										</a-typography-title>
										<a-space v-if="item.isDefault == 1 && currentRowId == item.addressId">
											<a-typography-text style="margin-top: 0%;"
												@click="updateUserAddress(currentRowId)">
												编辑
											</a-typography-text>
										</a-space>
										<a-space v-else-if="item.isDefault == 0 && currentRowId == item.addressId">
											<a-typography-text style="margin-top: 0%;"
											@click="setDefaultAddress(currentRowId)">
												设为默认地址
											</a-typography-text>
											<a-typography-text style="margin-top: 0%;"
												@click="updateUserAddress(currentRowId)">
												编辑
											</a-typography-text>
											<a-typography-text style="margin-top: 0%;"
											@click="deleteAddress(currentRowId)">
												删除
											</a-typography-text>
										</a-space>
									</a-col>
								</a-row>
							</div>
							<a-row style="margin-top: 0.5%;margin-bottom: 1%;cursor: pointer;position: relative;"
								v-show="addressList.data.length > 0" v-if="addressList.data">
								<a-col :span="4" style="text-align: left;white-space: nowrap;text-indent: 1em;">
									<a-typography-title class="address-info gray" :heading="7" @click="showReceiver">
										更多地址
										<icon-double-down v-if="currentShowStatus == false" />
										<icon-double-up v-if="currentShowStatus == true" />
									</a-typography-title>
								</a-col>
								<a-col :span="20" style="text-align: left;text-indent: 1em;">
								</a-col>
							</a-row>
							<!--没有收货信息-->
							<a-result :status="null" v-if="addressList.data == null" v-show="addressList.data == null">
								<template #icon>
									<IconFaceFrownFill style="color: gray;" />
								</template>
								<template #title>这里什么也没有哦</template>
								<a-typography style="background: var(--color-fill-2); padding: 24px;">
									<a-typography-paragraph>你还没有收货信息</a-typography-paragraph>
									<ul style="text-align: left;">
										<li> 你可以新增收货信息 </li>
									</ul>
								</a-typography>
							</a-result>
						</a-list-item>
						<!--第三步骤时显示的地址内容-->
							<a-list-item style="height:auto;" v-if="currentStep == 3">
								<a-row style="height: 24px;">
									<a-col :span="12" style="text-align: left;">
										<a-typography-title :heading="7" style="font-weight: bold;margin-top: 0%;">
											收货人信息
										</a-typography-title>
									</a-col>
									<a-col :span="12" style="text-align: right;">
										
									</a-col>
								</a-row>
						
								<div style="overflow: auto;min-height: 60px;max-height: 90px;"
									v-show="addressList.data.length > 0" v-if="addressList.data">
									<a-row style="margin-top: 0.5%;margin-bottom:1%;cursor: pointer;"
										v-for="(item,index) in addressList.data">
										<a-col :span="4" style="text-align: left;white-space: nowrap;text-indent: 1em;"
										v-if="currentcheckedId == item.addressId">
											<a-typography-title class="address-info" :heading="7"
												@click="chooseReceiver(item)">
												<div
													style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;width: 165px;">
													{{item.name}} {{item.telePhone}}
												</div>
												<span v-if="currentcheckedId == item.addressId">
													<div id="triangle"></div>
													<div class="check">
														<icon-check />
													</div>
												</span>
											</a-typography-title>
										</a-col>
										<a-col :span="20" style="text-align: left;text-indent: 1em;" v-if="currentcheckedId == item.addressId">
											<a-typography-title class="address-detail"  :heading="7" 
											ellipsis>
												{{item.address}}
												<a-tag style="text-indent: 0em;" v-if="currentcheckedId == item.addressId">
													<template #icon>
														<icon-check-circle-fill />
													</template>
													当前地址
												</a-tag>
											</a-typography-title>
											<a-space v-if="item.isDefault == 1 && currentRowId == item.addressId">
												<a-typography-text style="margin-top: 0%;"
													@click="updateUserAddress(currentRowId)">
													编辑
												</a-typography-text>
											</a-space>
											<a-space v-else-if="item.isDefault == 0 && currentRowId == item.addressId">
												<a-typography-text style="margin-top: 0%;">
													设为默认地址
												</a-typography-text>
												<a-typography-text style="margin-top: 0%;"
													@click="updateUserAddress(currentRowId)">
													编辑
												</a-typography-text>
												<a-typography-text style="margin-top: 0%;">
													删除
												</a-typography-text>
											</a-space>
										</a-col>
									</a-row>
								</div>
								<a-row style="margin-top: 0.5%;margin-bottom: 1%;cursor: pointer;position: relative;"
									v-show="addressList.data.length > 0" v-if="addressList.data">
									<a-col :span="4" style="text-align: left;white-space: nowrap;text-indent: 1em;">
										
									</a-col>
									<a-col :span="20" style="text-align: left;text-indent: 1em;">
									</a-col>
								</a-row>
							</a-list-item>
						<!-- 支付方式 -->
						<a-list-item v-if="currentStep == 1 || currentStep == 3">
							<a-row style="height: 24px;">
								<a-col :span="12" style="text-align: left;">
									<a-typography-title :heading="7" style="font-weight: bold;margin-top: 0%;">
										支付方式
									</a-typography-title>
								</a-col>
								<a-col :span="12" style="text-align: right;">
									<a-typography-text type="primary" style="margin-top: 0%;cursor: pointer;">
									</a-typography-text>
								</a-col>
							</a-row>
							<a-row style="margin-top: 0.5%;margin-bottom:2%;cursor: pointer;">
								<a-col :span="4"
									style="text-align: left;white-space: nowrap;text-indent: 1em;height: 22px;">
									<a-typography-title class="address-info" :heading="7">
										<a-row>
											<a-col :span="12">
												支付宝支付
											</a-col>
											<a-col :span="10" style="height: 22px;margin-top: -8px;margin-left: -10px;">
												<i class="iconfont iconfont-alipay" style="font-size: 22px;" />
											</a-col>
										</a-row>
										<span>
											<div id="triangle"></div>
											<div class="check">
												<icon-check />
											</div>
										</span>
									</a-typography-title>
								</a-col>
							</a-row>
						</a-list-item>
						<a-list-item v-if="currentStep == 2 || currentStep == 3">
							<a-row>
								<a-col :span="12" style="text-align: left;">
									<a-typography-title :heading="7" style="font-weight: bold;margin-top: 0%;">
										商品清单
									</a-typography-title>
								</a-col>
								<a-col :span="12" style="text-align: right;">
									<a-typography-text type="primary" style="margin-top: 0%;cursor: pointer;">
									</a-typography-text>
								</a-col>
							</a-row>
							<a-row style="margin-top: 0.5%;margin-bottom:1%;cursor: pointer;">
								<a-col :span="4" style="text-align: left;white-space: nowrap;text-indent: 1em;">
									<a-typography-title class="goods-info" :heading="7">
										<a-table :data="goodsList.data" style="width: 80.5vw;" ref="shoppingCart"
											:pagination="false">
											<template #columns>
												<a-table-column title="商品图片" :width="200">
													<template #cell="{record}">
														<div style="width: 120px;height: 120px;margin-left: -10px;">
															<img style="object-fit: cover;width: 100%;height: 100%;"
																:src="record.src" />
														</div>
													</template>
												</a-table-column>
												<a-table-column v-for="(item,index) in columns" :title="item.title"
													ellipsis>
													<template #cell="{record}">
														<a-tooltip :content="record[item.dataIndex].toString()"
															v-if="item.dataIndex == 'name' || item.dataIndex == 'info'"
															position="bottom" :arrow-style="{
																width: '0px',
																height: '0px'
															}">
															<span
																v-if="item.dataIndex == 'name' || item.dataIndex == 'info'"
																style="white-space: normal;">
																{{record[item.dataIndex]}}
															</span>
														</a-tooltip>
														<span v-if="item.dataIndex == 'sPrice'"
															style="white-space: normal;">
															{{record[item.dataIndex]}}
														</span>
													</template>
												</a-table-column>
												<a-table-column title="数量">
													<template #cell="{record}">
														{{record.amount}}
													</template>
												</a-table-column>
												<a-table-column title="金额">
													<template #cell="{record}">
														{{record.sPrice * record.amount}}
													</template>
												</a-table-column>
											</template>
										</a-table>
									</a-typography-title>
								</a-col>
							</a-row>
						</a-list-item>
						<a-list-item v-if="currentStep == 3">
							<a-row justify="end" style="text-align: right;">
								<a-space direction="vertical">
									<a-space direction="vertical" style="background-color: #ebebeb;width: 1235px;">
										<span v-if="goodsList.data">数量总计:
											<span
												style="font-weight: bold;color: red;">{{goodsList.data.length}}</span>件商品
										</span>
										<span>
											应付金额: {{total.toFixed(2)}}
										</span>
									</a-space>
									<!-- <a-row justify="end" style="text-align: right;">
										<a-space>
											<a-button type="primary" size="large" @click="router.go(-1)">
												返回上页
											</a-button>
											<a-button type="primary" v-if="total > 0" size="large" @click="toPay">
												提交订单
											</a-button>
										</a-space>
									</a-row> -->
								</a-space>
							</a-row>
						</a-list-item>
					</a-list>
					<a-row justify="center" style="text-align: right;" v-if="currentStep == 1">
						<a-space>
							<a-button type="primary" size="large" @click="backStep">
								返回上页
							</a-button>
							<a-button type="primary" v-if="total > 0" size="large" @click="nextStep">
								下一步
							</a-button>
						</a-space>
					</a-row>
					<a-row justify="center" style="text-align: right;" v-else-if="currentStep == 2">
						<a-space>
							<a-button type="primary" size="large" @click="backStep">
								返回上一步
							</a-button>
							<a-button type="primary" v-if="total > 0" size="large" @click="nextStep">
								下一步
							</a-button>
						</a-space>
					</a-row>
					<a-row justify="end" style="text-align: right;" v-else-if="currentStep == 3">
						<a-space>
							<a-button type="primary" size="large" @click="backStep">
								返回上一步
							</a-button>
							<a-button type="primary" v-if="total > 0" size="large" @click="toPay">
								提交订单
							</a-button>
						</a-space>
					</a-row>
				</a-layout-header>
			</a-config-provider>
		</a-layout>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance,
		onMounted,
		nextTick,
		watch
	} from 'vue';

	//国际化组件
	import enUS from '@arco-design/web-vue/es/locale/lang/en-us';
	import zhCN from '@arco-design/web-vue/es/locale/lang/zh-cn';

	import topBar from '@/components/index/topBar.vue';
	import userAddressForm from '@/components/orderDetail/addressForm.vue';
	import indexApi from '@/module/orderDetail/api/index.js';
	import moment from 'moment';
	import jwt_decode from 'jwt-decode';
	import { Modal } from '@arco-design/web-vue';

	let {
		proxy
	} = getCurrentInstance();

	import {
		useRouter,
		onBeforeRouteLeave
	} from 'vue-router';
	import {
		useRoute
	} from 'vue-router';
	let router = useRouter();
	let route = useRoute();

	let language = ref(zhCN);

	let loginformVisible = ref(false);
	let registerformVisible = ref(false);

	let chosenList = reactive(['单品', '系列', '厂商']);
	let currentKey = ref('0');

	let currentShowStatus = ref(false);
	let addressList = reactive({});
	let currentRowId = ref('0');
	let currentcheckedId = ref(0);

	let goodsList = reactive([]);
	let total = ref(0);
	let shoppingCart = ref(null);

	let currentStep = ref(1);
	let status = ref([]);

	let columns = reactive([{
			title: '商品名称',
			dataIndex: 'name'
		},
		{
			title: '商品信息',
			dataIndex: 'info'
		},
		{
			title: '单价',
			dataIndex: 'sPrice'
		}
	]);

	let addressformVisible = ref(false);
	let addressForm = reactive({
		name: '',
		telePhone: '',
		address: ''
	});
	let uId = ref();
	let orderDto = reactive({});
	let orderList = reactive({});
	let currentAddress = reactive({});
	let defaultStatus = reactive({});
	let deleteStatus = reactive({});
	
	function refurshAddressList(data){
		if(data == true){
			currentShowStatus.value = false;
			nextTick(()=>{
				loadingaddressList();
			});
		}
	}
	
	function nextStep(){
		//步骤为一和二时,可以进行下一步。如果为步骤一时,至少应该有一个地址被选择。
		if(currentStep.value == 1 && currentcheckedId.value != 0){
			currentStep.value = ++currentStep.value;
			console.log('nextStep',currentStep.value);
		}
		else if(addressList.resp.length == 0){
			proxy.$message.warning('请先添加你的收货信息');
		}
		else if(currentStep.value == 2){
			currentStep.value = ++currentStep.value;
			console.log('nextStep',currentStep.value);
		}
	}
	
	async function backStep(){
		if(currentStep.value != 1){
			currentStep.value = --currentStep.value;
			console.log('backStep',currentStep.value);
		}
		else if(currentStep.value == 1){
			let waitOrderStatus = reactive({});
			waitOrderStatus.resp = await indexApi.createWaitOrder(uId.value,route.params.id);
			router.go(-1);
		}
	}

	async function toPay() {
		console.log('当前用户id:', uId.value);
		console.log('当前订单号:', route.params.id);
		if(total.value > 0){
			orderList.resp = await indexApi.payOrder(uId.value,orderDto);
			orderList.data = orderList.resp.data;
			orderList.flag = orderList.resp.flag;
			console.log('orderList',orderList.resp);
			const div = document.createElement('div');
			div.innerHTML = orderList.data;
			document.body.appendChild(div);
			document.forms[0].submit();
		}
	}

	function insertAddress() {
		addressformVisible.value = true;
		status.value.splice(0, status.value.length);
		status.value.push('1');
	}

	function changeLanguage() {
		console.log('当前语言', language.value);
		if (language.value.locale != '' && language.value.locale != null && language.value.locale == 'zh-CN') {
			language.value = enUS;

			proxy.$i18n.locale = 'en';
		} else {
			language.value = zhCN;

			proxy.$i18n.locale = 'zh';
		}
		console.log('切换后语言', language.value);
	}

	function changeThemeColor() {
		if (document.body.getAttribute('arco-theme') == 'dark') {
			document.body.removeAttribute('arco-theme');
			document.documentElement.style.setProperty('--color-content', '#fcfcfc');
			document.documentElement.style.setProperty('--color-content-a', '#4c4c4c');
			document.documentElement.style.setProperty('--color-font', '#4c4c4c');

		} else {
			document.body.setAttribute('arco-theme', 'dark');
			document.documentElement.style.setProperty('--color-content', '#4c4c4c');
			document.documentElement.style.setProperty('--color-content-a', '#f4f4f4');
			document.documentElement.style.setProperty('--color-font', '#f4f4f4');
		}
	}

	function getTab(key) {
		console.log('key', key);
		console.log('chosen', chosenList[key])
		currentKey.value = key;
		switch (chosenList[key]) {
			case '单品':
				router.push({
					name: 'goods'
				});
				break;
			case '系列':
				router.push({
					name: 'series'
				});
				break;
			case '厂商':
				router.push({
					name: 'firm'
				});
				break;
		}
	}

	function getloginData(data) {
		loginformVisible.value = data;
		console.log('loginVisable', data);
	}

	function getregisterData(data) {
		registerformVisible.value = data;
		console.log('registerVisable', data);
	}

	function addressVisible(data) {
		addressformVisible.value = data;
		if (addressformVisible.value == true)
			currentShowStatus.value = true;
	}

	function showReceiver() {
		currentShowStatus.value = !currentShowStatus.value;
		console.log('currentShowStatus', currentShowStatus.value);
		//点击更多地址时
		if (currentShowStatus.value == true) {
			addressList.resp.data.map(item => {
				if (item.isDefault == 0) {
					addressList.data.push(item);
				}
			});
		}
		//收起地址时 
		else if (currentShowStatus.value == false) {
			addressList.data = addressList.data.filter((item, index) => {
				if (item.isDefault == 1) {
					return item;
				}
			});
		}
	}

	function hoverReceiver(item) {
		currentRowId.value = item.addressId;
	}

	function leaveReceiver(item) {
		currentRowId.value = '0';
	}

	function chooseReceiver(item) {
		currentcheckedId.value = item.addressId;
		console.log('addressId', currentcheckedId.value);
	}

	function updateUserAddress(addressId) {
		if (currentcheckedId.value == addressId) {
			console.log('addressId', addressId);
			addressformVisible.value = true;
			status.value.splice(0, status.value.length);
			status.value.push('0');
			currentAddress.data = addressList.data.filter(item =>{
				if(item.addressId == addressId){
					return item;
				}
			});
			console.log('currentAddress',currentAddress.data);
		} else {
			proxy.$message.warning('请先勾选收货人!');
		}
	}
	
	async function setDefaultAddress(addressId){
		if (currentcheckedId.value == addressId) {
			console.log('addressId', addressId);
			defaultStatus.resp = await indexApi.setDefaultAddress(addressId);
			console.log('defaultStatus.resp',defaultStatus.resp);
			if(defaultStatus.resp.flag == true){
				nextTick(()=>{
					loadingaddressList();
				});
				proxy.$message.success('设置默认地址成功');
				currentShowStatus.value = false;
			}
		} else {
			proxy.$message.warning('请先勾选收货人!');
		}
	}
	
	function deleteAddress(addressId){
		if (currentcheckedId.value == addressId) {
			console.log('addressId', addressId);
			Modal.open({
			        title: '警告',
			        content: '确定要删除收货人信息吗?',
					async onOk(){
						deleteStatus.resp = await indexApi.deleteAddress(addressId);
						console.log('deleteStatus.resp',deleteStatus.resp);
						if(deleteStatus.resp.flag == true){
							nextTick(()=>{
								loadingaddressList();
							});
							currentShowStatus.value = false;
						}
					}
			      });
		} else {
			proxy.$message.warning('请先勾选收货人!');
		}
	}

	async function loadingaddressList() {
		uId.value = jwt_decode(sessionStorage.getItem("token")).uid;
		addressList.resp = await indexApi.getaddressList(uId.value);
		if(addressList.resp.hasOwnProperty('data')){
			if(addressList.resp.data){
				addressList.data = addressList.resp.data.filter((item, index) => {
					if (item.isDefault == 1) {
						currentcheckedId.value = item.addressId;
						console.log('addressId', currentcheckedId.value);
						loadingGoodsList();
						return item;
					}
				});
			}
			else{
				addressList.resp.length = 0;
			}
			console.log('addressList.resp', addressList.resp);
		}
		return addressList;
	}

	async function loadingGoodsList() {
		uId.value = jwt_decode(sessionStorage.getItem("token")).uid;
		console.log('orderId', route.params.id);
		goodsList.resp = await indexApi.getOrderGoodsList(uId.value, route.params.id);
		goodsList.data = goodsList.resp.data;
		goodsList.flag = goodsList.resp.flag;
		if (goodsList.flag == true) {
			goodsList.data.map((item) => {
				total.value = total.value + (item.sPrice * item.amount);
			});
		}
		if (goodsList.flag == false) {
			proxy.$message.error('请不要随意修改订单')
			router.push({
				name: 'error'
			})
		}
		let date = new Date();
		orderDto = { //商户订单号
			out_trade_no: route.params.id,
			//订单名称
			subject: `用户${jwt_decode(sessionStorage.getItem("token")).nam}在${proxy.moment().format('YYYY年MM月DD日 HH:mm:ss')}提交的的订单`,
			//付款金额
			total_amount: total.value.toFixed(2).toString(),
			//商品描述
			body: `${goodsList.data[0].name}等${goodsList.data.length}件商品`,
			//超时时间
			timeout_express: '15m',
			//收货地址id
			passback_params: currentcheckedId.value
		}
		console.log('orderDto',orderDto);
		console.log('goodsList.resp', goodsList.resp);
		console.log('goodsList', goodsList.data);
	}

	onBeforeRouteLeave((to, from) => { //离开当前的组件，触发
		console.log('to', to.fullPath);
	})

	onMounted(() => {
		console.log('orderDetail的onMounted执行了');
		document.documentElement.style.setProperty('--color-content', '#f4f4f4');
		document.documentElement.style.setProperty('--color-font', 'gray');
		loadingaddressList();
		console.log('env',
			import.meta.env);
	});
</script>

<style lang="less" scoped>
	@import '@/assets/orderDetail/css/index.less';
</style>
